import { useMemberStore } from '@/stores'
import type { loginResult } from '@/types/member'
import { request } from '@/utils/request'

type loginParams = {
  code: string
  login_code: string
}

export const testLoginApi = (phone: string) => {
  return request<loginResult>({
    method: 'POST',
    url: '/login/testLogin',
    data: {
      phone,
    },
  })
}

/**
 * 获取登录用户session
 * @param login_code
 * @returns
 */
export const getSessionByLoginCodeApi = (login_code: string) => {
  return request<{
    openid: string
    unionid: string
  }>({
    method: 'GET',
    url: '/login/getSessionByLoginCode',
    data: {
      login_code,
    },
  })
}

/**
 * 微信登录
 */
export const miniAppLoginApi = (data: loginParams) => {
  return request<loginResult>({
    method: 'POST',
    url: '/login/miniAppLogin',
    data,
  })
}

export const checkLoginIegalityApi = (login_code: string) => {
  return request<{
    login_by_phone: boolean
  }>({
    method: 'POST',
    url: '/login/checkLoginIegality',
    data: {
      login_code,
    },
  })
}

export const quickLoginApi = (login_code: string) => {
  return request<loginResult>(
    {
      method: 'POST',
      url: '/login/quickLogin',
      data: {
        login_code,
      },
    },
    false,
    false,
  )
}

export const logout = () => {
  return request({
    method: 'POST',
    url: '/login/logout',
    data: {
      refresh_token: useMemberStore().profile?.refresh_token,
    },
  })
}

export const loginByPhone = (data: { phone: string; sms_captcha_code: string }) => {
  return request<loginResult>({
    method: 'POST',
    url: '/login/phone',
    data,
  })
}

export const loginByPassword = (data: { username: string; password: string }) => {
  return request<loginResult>({
    method: 'POST',
    url: '/login/password',
    data,
  })
}

export const registerApi = (data: {
  username: string
  password: string
  phone: string
  sms_captcha_code: string
}) => {
  return request<loginResult>({
    method: 'POST',
    url: '/login/register',
    data,
  })
}
